/**
 *
 * lua脚本集合
 *
 * 用于一些对redis原有数据有执行依赖的事务
 *
 * @author {cmx}
 */

// redis连接，本身不创建，由外部传入。
let redisClient;

let instance = {
    script: {}
};

/**
 * 抢红包动作的脚本定义（keysLength值为KEY的个数）
 *
 * KEYS[1]      全局分红key
 * ARGV[1]      分红数额
 *
 * @return 1 成功  -1 失败1
 */
instance.script.grabbingProfit = {
    code: `
    local surplus = redis.call("GET", KEYS[1])
    surplus = tonumber(surplus)
    local oil = ARGV[1]
    oil = tonumber(oil)
    if surplus > oil then 
        local current = surplus - oil
        if redis.call("SET", KEYS[1], current) then
            return 1
        else
            return -1
        end
    else 
         return -1
    end
  `,
    keysLength: 1
};


/**
 * lua执行器
 * @param name
 * @param param
 * @returns {Promise<unknown>}
 */
instance.run = function (name, ...param) {
    return new Promise((resolve, reject) => {
        if (!redisClient) {
            reject('redisClient is no ready');
        } else if (!instance.script[name]) {
            reject('this command is not supported');
        } else {
            redisClient.script('load', instance.script[name].code, (err, sha) => {
                if (err) {
                    reject(err);
                } else {
                    redisClient.evalsha(sha, instance.script[name].keysLength, ...param, (err, result) => {
                        if (err) {
                            reject(err);
                        } else {
                            resolve(result);
                        }
                    });
                }
            });
        }
    });
}

module.exports = function (client) {
    if (!client) {
        return;
    }
    redisClient = client;
    return instance;
}